//
//  WBOAuthViewController.swift
//  仿新浪微博
//
//  Created by 罗超 on 2017/8/21.
//  Copyright © 2017年 LuoChao. All rights reserved.
//

import UIKit
import SVProgressHUD

// 通过 webView 加载新浪微博授权页面控制器
class WBOAuthViewController: UIViewController {
    
    fileprivate lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        view.backgroundColor = UIColor.white
        
        // 新浪微博服务器返回授权页面默认全屏，所以不需要滚动
        webView.scrollView.isScrollEnabled = false
        
        webView.delegate = self
        
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        guard let url = URL(string: urlString) else {
            return
        }
        let request = URLRequest(url: url)
        webView.loadRequest(request)
        
    }

    // 监听方法
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    // 自动填充 - WebView 的注入，直接通过 js 修改“本地浏览器中”缓存的页面内容
    @objc fileprivate func autoFill() {
        let jsStr = "document.getElementById('userId').value = '18575595838';" + "document.getElementById('passwd').value = 'luochao19901016';"
        
        webView.stringByEvaluatingJavaScript(from: jsStr)
    }
}

extension WBOAuthViewController: UIWebViewDelegate {
    
    /// 将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 如果包含 http://baidu.com 则不加载页面 / 否则加载页面
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
            return true
        }
        // 从 http://baidu.com 回调地址字符串中查找 “code=”,如果有则授权成功，没有则失败
        // query 就是 URL 中 “?” 后面的所有部分
        if request.url?.query?.hasPrefix("code=") == false {
            close()
            return false
        }
        // 获取 code
        //let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""  //iOS 11 已弃用，会警告
        let startIndex = "code=".endIndex
        guard let endIndex: String.Index = request.url?.query?.endIndex,
        let code = request.url?.query?[startIndex..<endIndex]
            else {
            return false
        }
        WBNetworkManager.shared.loadAccessToken(code: String(code))
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
